const query = require('./db.js')
const util = require('../util/util.js')
// 用户类
class User {
  // 创建新数据
  static createNew(model) {
    return {
      userName: model.userName,
      passWord: model.passWord,
      trueName: model.trueName,
      salt: model.salt,
      telephone: model.telephone,
      email: model.email,
      state: 1, // 1正常，2禁用
      lastLoginTime: 0,
      lastLoginIp: ''
    }
  }
  // 添加用户数据
  static create(arr, callBack) {
    const sqlData = util.convertSQLInsert(arr)
    let sql = `INSERT INTO app_user ${sqlData}; `
    query(sql, (err, res) => {
      if (err) {
        callBack(err, null)
        return
      }
      callBack()
    })
  }
  // 根据ID查询数据
  static getById(id, callBack) {
    query(`SELECT id,userName,state,lastLoginTime,lastLoginIp,trueName,telephone,email FROM app_user WHERE id = ${id};`, (err, res) => {
      if (err) {
        callBack(err, null)
        return
      }
      callBack(null, res[0])
    })
  }
  // 根据用户名查询数据
  static getByName(useName, callBack) {
    query(`SELECT * FROM app_user WHERE userName = "${useName}";`, (err, res) => {
      if (err) {
        callBack(err, null)
        return
      }
      callBack(null, res[0])
    })
  }
  // 获取用户列表
  static getList(callBack) {
    query(`SELECT id,userName,state,lastLoginTime,lastLoginIp FROM app_user;`, (err, res) => {
      if (err) {
        callBack(err, null)
        return
      }
      callBack(null, res)
    })
  }
  // 更新指定用户数据
  static updateById(data, callBack) {
    const sqlData = util.convertSQLUpdate(data)
    query(`UPDATE app_user SET ${sqlData} WHERE id = ${data.id};`, (err, res) => {
      if (err) {
        callBack(err, null)
        return
      }
      if (res.affectedRows == 0) {
        callBack({ message: '未找到用户信息'}, null)
        return
      }
      callBack();
    })
  }
  // 删除指定用户数据
  static delete(id, callBack) {
    query(`DELETE FROM app_user WHERE id = ${id};`, (err, res) => {
      if (err) {
        callBack(err, null)
        return
      }
      if (res.affectedRows == 0) {
        callBack({ message: '未找到用户信息'}, null)
        return
      }
      callBack(null, res);
    })
  }
  // 设置角色
  static setRole(userId, data, callBack) {
    query(`DELETE FROM user_role WHERE userId = ${userId};`, (err, res) => {
      if (err) {
        callBack(err, null)
        return
      }
      const sqlData = util.convertSQLInsert(data)
      let sql = `INSERT INTO user_role ${sqlData};`
      query(sql, (err2, res2) => {
        if (err2) {
          callBack(err2, null)
          return
        }
        callBack(null, res2);
      })
    })
  }
}
module.exports = User